﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Globalization;
using System.Linq;
using System.Runtime.Caching;
using System.Text;

namespace System.Runtime.Caching
{
    /// <summary>
    /// EF ChangeMonitor实现
    /// </summary>
    public class SqlEFChangeMonitor : ChangeMonitor
    {
        private readonly string _uniqueId;
        public override string UniqueId
        {
            get
            {
                return this._uniqueId;
            }
        }
        public SqlEFChangeMonitor(SqlCommand command, string connectionString)
        {
            bool flag = true;
            try
            {
                var sqlDependency = new SqlDependency(command);
                sqlDependency.OnChange += new OnChangeEventHandler(this.OnDependencyChanged);
                this._uniqueId = Guid.NewGuid().ToString("N", CultureInfo.InvariantCulture);
                SqlDependencyManager.AddConnectionString(connectionString);
                RegisterNotification(command, connectionString);
                flag = false;
            }
            finally
            {
                InitializationComplete();
                if (flag)
                {
                    Dispose();
                }
            }
        }

        private void RegisterNotification(SqlCommand command, string connectionString)
        {
            using (var connection = new SqlConnection(connectionString))
            {
                command.Connection = connection;
                connection.Open();
                // NOTE: You have to execute the command, or the notification will never fire.
                using (SqlDataReader reader = command.ExecuteReader())
                {
                }
            }
        }

        private void OnDependencyChanged(object sender, SqlNotificationEventArgs e)
        {
            base.OnChanged(null);
        }
        protected override void Dispose(bool disposing)
        {
        }
    }
}
